package com.tongle.frs.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils
{
  public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, String path, int maxage, String domain)
  {
    Cookie cookie = new Cookie(name, value);
    if ((path != null) && (path.length() > 0)) {
      cookie.setPath(path);
    } else {
      path = StringUtils.isBlank(request.getContextPath()) ? "/" : request.getContextPath();
      cookie.setPath(path);
    }
    if ((domain != null) && (domain.length() > 0)) {
      cookie.setDomain(domain);
    }
    if (maxage >= 0) {
      cookie.setMaxAge(maxage);
    }
    response.addCookie(cookie);
  }

  public static String getCookie(HttpServletRequest request, String name)
  {
    String returnValue = null;
    Cookie[] cookies = request.getCookies();
    Cookie cookie = null;
    if ((cookies != null) && (cookies.length > 0)) {
      for (int i = 0; i < cookies.length; i++) {
        cookie = cookies[i];
        if (name.equalsIgnoreCase(cookie.getName().trim())) {
          returnValue = cookie.getValue();
          break;
        }
      }
    }
    return returnValue;
  }

  public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, String domain)
  {
    addCookie(request, response, name, null, path, 0, domain);
  }
}